// 学习记录页面逻辑
Page({
  data: {
    totalStudyDays: 0,
    totalQuestions: 0,
    correctRate: '0%',
    currentFilter: 'all',
    studyHistory: [],
    loading: false,
    hasMore: true,
    page: 1,
    pageSize: 10
  },

  onLoad: function (options) {
    this.loadStatistics();
    this.loadStudyHistory();
  },

  // 加载统计数据
  loadStatistics: function () {
    const studyHistory = wx.getStorageSync('studyHistory') || [];
    
    // 计算总题数（从题库中获取）
    const { questionCategories } = require('../../utils/questions.js');
    let totalQuestions = 0;
    questionCategories.forEach(category => {
      category.topics.forEach(topic => {
        totalQuestions += topic.questions.length;
      });
    });
    
    // 计算学习天数
    const studyDays = this.calculateStudyDays(studyHistory);
    
    // 计算已做题目数和正确率
    let completedQuestions = 0;
    let correctCount = 0;
    studyHistory.forEach(record => {
      completedQuestions += record.questionCount || 0;
      correctCount += record.correctCount || 0;
    });
    const correctRate = completedQuestions > 0 ? Math.round((correctCount / completedQuestions) * 100) + '%' : '0%';
    
    this.setData({
      totalStudyDays: studyDays,
      totalQuestions: completedQuestions, // 显示已做题目数
      correctRate: correctRate
    });
  },

  // 计算学习天数
  calculateStudyDays: function (studyHistory) {
    if (studyHistory.length === 0) return 0;
    
    const dates = new Set();
    studyHistory.forEach(record => {
      if (record.date) {
        dates.add(record.date);
      }
    });
    
    return dates.size;
  },

  // 加载学习记录
  loadStudyHistory: function (isLoadMore = false) {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    // 获取真实的学习记录
    const allHistory = wx.getStorageSync('studyHistory') || [];
    
    // 根据筛选条件过滤
    const filteredHistory = this.filterHistory(allHistory, this.data.currentFilter);
    
    // 分页处理
    const startIndex = isLoadMore ? this.data.studyHistory.length : 0;
    const endIndex = startIndex + this.data.pageSize;
    const newHistory = filteredHistory.slice(startIndex, endIndex);
    
    if (isLoadMore) {
      this.setData({
        studyHistory: [...this.data.studyHistory, ...newHistory],
        hasMore: endIndex < filteredHistory.length
      });
    } else {
      this.setData({
        studyHistory: newHistory,
        hasMore: endIndex < filteredHistory.length
      });
    }
    
    this.setData({ loading: false });
  },

  // 筛选学习记录
  filterHistory: function (history, filter) {
    if (filter === 'all') {
      return history;
    }
    
    const today = new Date().toDateString();
    const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000).toDateString();
    const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toDateString();
    const monthAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toDateString();
    
    return history.filter(record => {
      const recordDate = new Date(record.timestamp || record.date).toDateString();
      
      switch (filter) {
        case 'today':
          return recordDate === today;
        case 'week':
          return new Date(recordDate) >= new Date(weekAgo);
        case 'month':
          return new Date(recordDate) >= new Date(monthAgo);
        default:
          return true;
      }
    });
  },

  // 设置筛选条件
  setFilter: function (e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      currentFilter: type
    });
    this.loadStudyHistory();
  },

  // 跳转到详情
  goToDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/history-detail/history-detail?id=${id}`
    });
  },

  // 跳转到练习页面
  goToPractice: function () {
    wx.switchTab({
      url: '/pages/practice/practice'
    });
  },

  // 加载更多
  loadMore: function () {
    if (this.data.hasMore && !this.data.loading) {
      this.loadStudyHistory(true);
    }
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    this.loadStatistics();
    this.loadStudyHistory();
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom: function () {
    this.loadMore();
  }
}); 